﻿#include "cserver.h"

CServer::CServer():m_server(NULL)
{
    m_server = new QLocalServer;
    connect(m_server, SIGNAL(newConnection()), SLOT(serverNewConnectionHandler()));
}

CServer::~CServer()
{
    m_server->close();
    delete m_server;
}

void CServer::RunServer()
{
    qDebug() << "Run Server ok";

    QLocalServer::removeServer("\\\\.\\pipe\\clpdpipe");//\\\\.\\pipe\\clpdpipe
    bool ok = m_server->listen("\\\\.\\pipe\\clpdpipe");
    if (!ok)
    {
        qDebug() << "Listen Failed";
        // TODO:
    }
}

void CServer::serverNewConnectionHandler()
{
    qDebug() << "New Connection";
    qDebug() << "listen: " << m_server->serverName();

    QLocalSocket* socket = m_server->nextPendingConnection();
    connect(socket, SIGNAL(readyRead()), this, SLOT(socketReadyReadHandler()));
    connect(socket, SIGNAL(disconnected()), socket, SLOT(deleteLater()));
}

void CServer::socketReadyReadHandler()
{
    QLocalSocket* socket = static_cast<QLocalSocket*>(sender());
    if (socket)
    {
        QTextStream stream(socket);
        qDebug() << "Read Data From Client:" << stream.readAll();

        QString response = "Hello Client";
        socket->write(response.toUtf8());
        socket->flush();
    }
    // 返回到客户端的void sendMessage 方法，m_socket->waitForReadyRead()之后的操作
}


